Exploring the core concepts of executable code and object-oriented structure.
A **function** is a block of reusable code that performs a specific task. A **class** is a blueprint for creating objects. It encapsulates data and functions that operate on that data into a single unit.
function greet(name) { return `Hello, ${name}!`; } class Person { constructor(name) { this.name = name; } sayHello() { return `Hello from ${this.name}`; } }
Result of `greet("Alice")`:
An `async` function operates asynchronously via the event loop. It always returns a **Promise**. The `await` keyword can only be used inside an `async` function to pause execution until a promise is resolved, making asynchronous code look and feel synchronous.
async function getData() { const response = await fetch('...'); return response.json(); }
Simulating an asynchronous operation with a 2-second delay.
A **generator function** (`function*`) can be paused and resumed, yielding a value on each pause. It returns a **generator object** (`Generator`), which is an iterator. This is useful for creating iterable sequences and managing state in a single function.
function* count() { yield 1; yield 2; yield 3; } const counter = count();
Click `Next Step` to run the generator to the next `yield` statement.
An **async generator function** combines the features of async functions and generator functions. It allows you to pause and resume execution while also waiting for promises to resolve, creating asynchronous iterable sequences.
async function* fetchNumbers() { yield await someAsyncCall(); }
Simulating an async generator yielding values with delays.